<template>
  <div>
    <div v-if="!showIframe" class="apply-container">
      <div class="job-detail">
        <div class="job-header">
          <h2>{{ jobDetail.name }}</h2>
          <el-button v-if="jobDetail && jobDetail.state === 4" type="primary" @click="handleApply">申请职位</el-button>
        </div>
        <div class="job-meta">
          <div class="meta-item">
            <span class="label">工作经验：</span>
            <span>{{ formatWorkExperience(jobDetail.workExperience) }}</span>
          </div>
          <div class="meta-item">
            <span class="label">学历要求：</span>
            <span>{{ formatDegree(jobDetail.degree) }}</span>
          </div>
          <div class="meta-item">
            <span class="label">年龄要求：</span>
            <span>{{ jobDetail.age }}</span>
          </div>
          <div class="meta-item">
            <span class="label">招聘人数：</span>
            <span>{{ jobDetail.num }}人</span>
          </div>
          <div class="meta-item">
            <span class="label">工作地点：</span>
            <span>{{ jobDetail.address }}</span>
          </div>
          <div class="meta-item">
            <span class="label">截止时间：</span>
            <span>{{ dayjs(jobDetail.deadline).format('YYYY-MM-DD') }}</span>
          </div>
        </div>
        <div class="job-section">
          <h3>专业要求</h3>
          <div class="content">{{ jobDetail.major || '不限' }}</div>
        </div>

        <div class="job-section">
          <h3>职位描述</h3>
          <div class="content" v-html="formatContent(jobDetail.description)"></div>
        </div>

        <div class="job-section">
          <h3>更多信息</h3>
          <el-tag v-for="tag in jobDetail.customizationList" :key="tag" type="" style="margin-right: 10px;">{{ tag
            }}</el-tag>
        </div>
      </div>
    </div>
    <div v-else class="iframe-container" v-loading="formLoading" element-loading-text="表单加载中">
      <iframe ref="applyIframe" class="apply-iframe" :src="formUrl" @load="handleIframeLoad"></iframe>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { selectPostById, selectFormLink } from '@/api/position'
import { encrypt } from '@ruifox-cms/utils'
import dayjs from 'dayjs'

const route = useRoute()
const showIframe = ref(false)

// 模拟职位详情数据
const jobDetail = ref({})
const handleGetJobDetail = async () => {
  const res = await selectPostById({ id: route.query.jobId })
  if (res.code === 20000) {
    jobDetail.value = res.data
  }
}

// 格式化学历
const formatDegree = (degree) => {
  const DEGREE_MAP = {
    '1': '博士',
    '2': '硕士',
    '3': '本科',
    '4': '大专',
    '5': '不限'
  }
  return DEGREE_MAP[degree] || '不限'
}

// 格式化工作经验
const formatWorkExperience = (experience) => {
  const WORK_EXPERIENCE_MAP = {
    '1': '应届生',
    '2': '1-3年',
    '3': '3-5年',
    '4': '5-10年',
    '5': '10年以上',
    '6': '不限'
  }
  return WORK_EXPERIENCE_MAP[experience] || '不限'
}

// 格式化内容（将\n转换为<br>）
const formatContent = (content) => {
  if (Array.isArray(content)) {
    return content.join('<br>')
  }
  return content?.replace(/\n/g, '<br>') || ''
}

// 处理申请按钮点击
const formUrl = ref('')
const formLoading = ref(false)
const handleApply = async () => {
  const res = await selectFormLink({ formId: jobDetail.value.paperId })
  if (!res.data.link) {
    ElMessage.error('申请表获取失败')
    return
  }
  let link
  if (process.env.NODE_ENV === 'development') {
    link = location.protocol + '//' + location.hostname + ':8080/?formKey=' + res.data.link
  } else {
    link = location.origin + '/formFront?formKey=' + res.data.link
  }
  const callbackQuery = encrypt({
    callbackUrl: '/recruitment/record/insert',
    sourceSystem: 'recruitment',
    timestamp: dayjs().unix(),
    data: {
      postId: route.query.jobId
    }
  })
  // 设置iframe的src
  formUrl.value = `${link}&callback=${callbackQuery}`
  showIframe.value = true
  formLoading.value = true
}

const applyIframe = ref(null)

// 处理iframe加载完成后的逻辑
const handleIframeLoad = () => {
  if (!applyIframe.value) return
  formLoading.value = false
  // 添加消息监听
  window.addEventListener('message', (event) => {
    const { type, height } = event.data
    if (type === 'form-setHeight' && height) {
      applyIframe.value.style.height = `${height}px`
    }
  })
}

// 添加窗口大小改变的监听
const handleResize = () => {
  if (showIframe.value) {
    handleIframeLoad()
  }
}

onMounted(async () => {
  if (route.query.groupId) {
    localStorage.setItem('recruitment-groupId', route.query.groupId)
  }
  await handleGetJobDetail()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
})
</script>

<style lang="scss" scoped>
.apply-container {
  max-width: 1000px;
  margin: 0 auto;
}

.job-detail {
  background: #fff;
  border-radius: 4px;
  padding: 24px;

  .job-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 20px;
    border-bottom: 1px solid #f0f0f0;

    h2 {
      margin: 0;
      font-size: 20px;
      color: #333;
    }
  }

  .job-meta {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    margin-bottom: 24px;
    padding-bottom: 20px;
    border-bottom: 1px solid #f0f0f0;

    .meta-item {
      color: #666;
      font-size: 14px;

      .label {
        color: #999;
        margin-right: 8px;
      }
    }
  }

  .job-section {
    margin-bottom: 24px;

    &:last-child {
      margin-bottom: 0;
    }

    h3 {
      font-size: 16px;
      color: #333;
      margin: 0 0 12px;
    }

    .content {
      color: #666;
      line-height: 1.6;
      font-size: 14px;
    }
  }
}

.iframe-container {
  
}

.apply-iframe {
  width: 100%;
  min-height: calc(100vh - 100px);
  border: none;
  display: block;
  overflow: auto;
  transition: height 0.3s;
}

@media (max-width: 768px) {
  .apply-container {
    padding: 0 10px;
  }

  .job-detail {
    .job-meta {
      grid-template-columns: repeat(2, 1fr);
    }
  }
}
</style>
